/*
	File: data/scripts/scene_render-to-texture.nut
	Author: GameStart3d.com
*/

/*!
	@short	SceneRenderToTexture
	@author	GameStart3d.com
*/
class	SceneRenderToTexture
{

	screen_item				=	0
	screen_geo				=	0
	screen_mat				=	0

	main_camera				=	0
	rt_camera				=	0
	render_texture			=	0

	/*!
		@short	OnUpdate
		Called each frame.
	*/
	function	OnUpdate(scene)
	{
		SceneRegisterAsPropertyCallback(scene, g_render)
		

		// Switch to output texture and render.
		SceneSetCurrentCamera(g_scene, ItemCastToCamera(rt_camera))
		RendererSetViewItemAndApplyView(g_render, rt_camera)

		ScenePushRenderable(scene, g_render)

		RendererClearFrame(g_render, 0, 0, 0)

		local	viewport = RendererGetOutputDimensions(g_render)
		RendererSetViewport(g_render, 0.0, 0.0, TextureGetWidth(render_texture).tofloat()/viewport.x.tofloat(), TextureGetHeight(render_texture).tofloat()/viewport.y.tofloat())

		RendererRenderQueue(g_render)

		RendererGrabDisplayToTexture(g_render, render_texture)

		RendererClearClippingPlane(g_render)
		RendererClearFrame(g_render, 0, 0, 0)

		// Restore camera, output buffer and viewport.	
		SceneSetCurrentCamera(g_scene, ItemCastToCamera(main_camera))
		RendererSetViewItemAndApplyView(g_render, main_camera)

		RendererSetViewport(g_render, 0.0, 0.0, 1.0, 1.0)

		RendererRenderQueue(g_render)
		RendererRenderQueueReset(g_render)
	}

	/*!
		@short	OnSetup
		Called when the scene is about to be setup.
	*/
	function	OnSetup(scene)
	{
		screen_item = SceneFindItem(scene, "monitor_screen")
		screen_geo = ItemGetGeometry(screen_item)
		screen_mat = GeometryGetMaterialFromIndex(screen_geo, 0)

		main_camera = SceneFindItem(scene, "main_camera")
		rt_camera = SceneFindItem(scene, "render-to-texture_camera")

		SceneSetRenderless(scene, true)

		render_texture = NewTexture()	//MaterialGetTexture(screen_mat, 0)
		local	render_picture = NewPicture(1280, 600)
		TextureUpdate(render_texture, render_picture)
		MaterialSetTexture(screen_mat, 0, render_texture)
	}
}
